using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace EntityKit.Editor
{
    /// <summary>
    /// 重复资源检查窗口
    /// </summary>
    public class DuplicateAssetCheckerWindow : EditorWindow
    {
        private string m_SelectedFolderPath = "";
        private Dictionary<string, List<string>> m_DuplicateAssets = new Dictionary<string, List<string>>();
        private Vector2 m_ScrollPosition;
        private bool m_HasScanned = false;
        private bool m_NeedsRescan = false;
        
        // 添加样式定义
        private GUIStyle m_TitleStyle;
        private GUIStyle m_HeaderStyle;
        private GUIStyle m_BoxStyle;
        private GUIStyle m_FileNameStyle;
        private GUIStyle m_FilePathStyle;
        private GUIStyle m_ButtonStyle;
        private GUIStyle m_SmallButtonStyle;
        private GUIStyle m_SectionHeaderStyle;
        private GUIStyle m_EmptyStateStyle;
        private GUIStyle m_ResultHeaderStyle;
        
        // 缓存常用颜色
        private static readonly Color PRO_SKIN_TEXT_COLOR = new Color(0.8f, 0.8f, 0.8f);
        private static readonly Color PRO_SKIN_DIM_COLOR = new Color(0.6f, 0.6f, 0.6f);
        private static readonly Color LIGHT_SKIN_TEXT_COLOR = new Color(0.2f, 0.2f, 0.2f);
        private static readonly Color LIGHT_SKIN_DIM_COLOR = new Color(0.4f, 0.4f, 0.4f);
        
        private const string FOLDOUT_OPEN_PREFIX = "▼ ";
        private const string FOLDOUT_CLOSED_PREFIX = "▶ ";
        private Dictionary<string, bool> m_GroupFoldoutStates = new Dictionary<string, bool>();
        
        public static void ShowWindow()
        {
            var window = GetWindow<DuplicateAssetCheckerWindow>("重复资源检查"); 
            window.minSize = new Vector2(600, 400);
        }
        
        private void InitStyles()
        {
            if (m_TitleStyle == null)
            {
                m_TitleStyle = new GUIStyle(EditorStyles.largeLabel);
                m_TitleStyle.fontSize = 18;
                m_TitleStyle.fontStyle = FontStyle.Bold;
                m_TitleStyle.alignment = TextAnchor.MiddleCenter;
                m_TitleStyle.normal.textColor = EditorGUIUtility.isProSkin ? PRO_SKIN_TEXT_COLOR : LIGHT_SKIN_TEXT_COLOR;
            }
            
            if (m_HeaderStyle == null)
            {
                m_HeaderStyle = new GUIStyle(EditorStyles.boldLabel);
                m_HeaderStyle.fontSize = 14;
                m_HeaderStyle.margin = new RectOffset(0, 0, 5, 5);
            }
            
            if (m_BoxStyle == null)
            {
                m_BoxStyle = new GUIStyle(EditorStyles.helpBox);
                m_BoxStyle.padding = new RectOffset(10, 10, 10, 10);
                m_BoxStyle.margin = new RectOffset(0, 0, 5, 5);
            }
            
            if (m_FileNameStyle == null)
            {
                m_FileNameStyle = new GUIStyle(EditorStyles.boldLabel);
                m_FileNameStyle.fontSize = 13;
                m_FileNameStyle.padding = new RectOffset(5, 5, 5, 5);
            }
            
            if (m_FilePathStyle == null)
            {
                m_FilePathStyle = new GUIStyle(EditorStyles.textField);
                m_FilePathStyle.padding = new RectOffset(5, 5, 5, 5);
                m_FilePathStyle.wordWrap = true;
                m_FilePathStyle.clipping = TextClipping.Clip;
            }
            
            if (m_ButtonStyle == null)
            {
                m_ButtonStyle = new GUIStyle(GUI.skin.button);
                m_ButtonStyle.padding = new RectOffset(10, 10, 10, 10);
                m_ButtonStyle.margin = new RectOffset(5, 5, 5, 5);
            }
            
            if (m_SmallButtonStyle == null)
            {
                m_SmallButtonStyle = new GUIStyle(GUI.skin.button);
                m_SmallButtonStyle.padding = new RectOffset(5, 5, 5, 5);
                m_SmallButtonStyle.margin = new RectOffset(2, 2, 2, 2);
                m_SmallButtonStyle.fontSize = 11;
            }
            
            if (m_SectionHeaderStyle == null)
            {
                m_SectionHeaderStyle = new GUIStyle(EditorStyles.foldout);
                m_SectionHeaderStyle.fontStyle = FontStyle.Bold;
                m_SectionHeaderStyle.fontSize = 12;
            }
            
            if (m_EmptyStateStyle == null)
            {
                m_EmptyStateStyle = new GUIStyle(EditorStyles.label);
                m_EmptyStateStyle.fontSize = 14;
                m_EmptyStateStyle.alignment = TextAnchor.MiddleCenter;
                m_EmptyStateStyle.normal.textColor = EditorGUIUtility.isProSkin ? PRO_SKIN_DIM_COLOR : LIGHT_SKIN_DIM_COLOR;
            }
            
            if (m_ResultHeaderStyle == null)
            {
                m_ResultHeaderStyle = new GUIStyle(EditorStyles.boldLabel);
                m_ResultHeaderStyle.fontSize = 14;
                m_ResultHeaderStyle.margin = new RectOffset(0, 0, 0, 10);
            }
        }
        
        // 添加拖拽事件处理
        private void OnGUI()
        {
            InitStyles();
            HandleDragAndDrop();
            
            // 检查是否需要重新扫描
            if (m_NeedsRescan)
            {
                m_NeedsRescan = false;
                ScanForDuplicates();
            }
            
            OnBodyGUI();
        }

        protected void OnBodyGUI()
        {
            GUILayout.Space(10);
            
            EditorGUILayout.LabelField("重复资源检查工具", m_TitleStyle);
            EditorGUILayout.LabelField("选择一个文件夹来检查其中是否有同名的资源文件", EditorStyles.wordWrappedLabel);
            EditorGUILayout.LabelField("支持拖拽文件夹到窗口中", EditorStyles.wordWrappedMiniLabel);
            
            GUILayout.Space(10);
            
            // 文件夹选择区域
            GUILayout.BeginVertical(m_BoxStyle);
            EditorGUILayout.LabelField("📁 文件夹选择", m_HeaderStyle);
            
            GUILayout.BeginHorizontal();
            m_SelectedFolderPath = EditorGUILayout.TextField("检查路径", m_SelectedFolderPath);
            
            if (GUILayout.Button("浏览", GUILayout.Width(60)))
            {
                var folderPath = EditorUtility.OpenFolderPanel("选择要检查的文件夹", Application.dataPath, "");
                if (!string.IsNullOrEmpty(folderPath))
                {
                    // 转换为相对于Assets的路径
                    if (folderPath.Contains(Application.dataPath))
                    {
                        m_SelectedFolderPath = "Assets" + folderPath.Substring(Application.dataPath.Length);
                    }
                    else
                    {
                        ShowNotification(new GUIContent("请选择项目Assets文件夹内的路径"));
                    }
                }
            }
            GUILayout.EndHorizontal();
            
            GUI.enabled = !string.IsNullOrEmpty(m_SelectedFolderPath);
            if (GUILayout.Button("🔍 扫描重复资源", m_ButtonStyle))
            {
                ScanForDuplicates();
            }
            GUI.enabled = true;
            
            GUILayout.EndVertical();
            
            GUILayout.Space(10);
            
            // 显示扫描结果
            if (m_HasScanned)
            {
                DisplayScanResults();
            }
        }
        
        /// <summary>
        /// 处理拖拽事件
        /// </summary>
        private void HandleDragAndDrop()
        {
            Event evt = Event.current;
            if (evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform)
            {
                if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0)
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    
                    if (evt.type == EventType.DragPerform)
                    {
                        DragAndDrop.AcceptDrag();
                        
                        // 获取拖拽的第一个路径
                        string path = DragAndDrop.paths[0];
                        
                        // 检查是否为文件夹
                        if (Directory.Exists(Path.Combine(Application.dataPath, "..", path)))
                        {
                            // 保留原始路径，防止误删
                            m_SelectedFolderPath = path;
                            ShowNotification(new GUIContent("已设置文件夹路径"));
                            evt.Use();
                        }
                        else if (Directory.Exists(path))
                        {
                            // 处理绝对路径
                            string relativePath = "Assets" + path.Substring(Application.dataPath.Length);
                            m_SelectedFolderPath = relativePath;
                            ShowNotification(new GUIContent("已设置文件夹路径"));
                            evt.Use();
                        }
                        else if (File.Exists(Path.Combine(Application.dataPath, "..", path)))
                        {
                            // 如果是文件，则使用其所在的文件夹
                            m_SelectedFolderPath = Path.GetDirectoryName(path);
                            ShowNotification(new GUIContent("已设置文件所在文件夹路径"));
                            evt.Use();
                        }
                        else if (File.Exists(path))
                        {
                            // 处理绝对路径的文件
                            string relativePath = "Assets" + Path.GetDirectoryName(path).Substring(Application.dataPath.Length);
                            m_SelectedFolderPath = relativePath;
                            ShowNotification(new GUIContent("已设置文件所在文件夹路径"));
                            evt.Use();
                        }
                    }
                }
            }
        }
        
        /// <summary>
        /// 扫描指定文件夹中的重复资源
        /// </summary>
        private void ScanForDuplicates()
        {
            if (string.IsNullOrEmpty(m_SelectedFolderPath) || !Directory.Exists(Path.Combine(Application.dataPath, "..", m_SelectedFolderPath)))
            {
                ShowNotification(new GUIContent("请选择有效的文件夹路径"));
                return;
            }
            
            m_DuplicateAssets.Clear();
            m_GroupFoldoutStates.Clear();
            
            // 获取所有资源文件
            var allAssets = AssetDatabase.GetAllAssetPaths()
                .Where(path => path.StartsWith(m_SelectedFolderPath) && File.Exists(Path.Combine(Application.dataPath, "..", path)))
                .ToList();
            
            // 根据文件名分组
            var assetsByName = new Dictionary<string, List<string>>();
            
            foreach (var assetPath in allAssets)
            {
                var fileName = Path.GetFileName(assetPath);
                if (!assetsByName.ContainsKey(fileName))
                {
                    assetsByName[fileName] = new List<string>();
                }
                assetsByName[fileName].Add(assetPath);
            }
            
            // 只保留有重复的文件
            foreach (var pair in assetsByName)
            {
                if (pair.Value.Count > 1)
                {
                    m_DuplicateAssets[pair.Key] = pair.Value;
                    m_GroupFoldoutStates[pair.Key] = true; // 默认展开
                }
            }
            
            m_HasScanned = true;
            
            if (m_DuplicateAssets.Count > 0)
            {
                ShowNotification(new GUIContent($"找到 {m_DuplicateAssets.Count} 组重复资源"));
            }
            else
            {
                ShowNotification(new GUIContent("未找到重复资源"));
            }
        }
        
        /// <summary>
        /// 显示扫描结果
        /// </summary>
        private void DisplayScanResults()
        {
            GUILayout.BeginVertical(m_BoxStyle);
            
            if (m_DuplicateAssets.Count > 0)
            {
                EditorGUILayout.LabelField($"📊 找到 {m_DuplicateAssets.Count} 组重复资源:", m_ResultHeaderStyle);
                
                m_ScrollPosition = GUILayout.BeginScrollView(m_ScrollPosition);
                
                foreach (var pair in m_DuplicateAssets)
                {
                    GUILayout.BeginVertical(EditorStyles.helpBox);
                    
                    // 初始化折叠状态
                    if (!m_GroupFoldoutStates.ContainsKey(pair.Key))
                    {
                        m_GroupFoldoutStates[pair.Key] = true;
                    }
                    
                    // 可折叠的组标题
                    m_GroupFoldoutStates[pair.Key] = EditorGUILayout.Foldout(
                        m_GroupFoldoutStates[pair.Key], 
                        new GUIContent((m_GroupFoldoutStates[pair.Key] ? FOLDOUT_OPEN_PREFIX : FOLDOUT_CLOSED_PREFIX) + 
                                     $"📄 {pair.Key} ({pair.Value.Count} 个实例)"), 
                        true, m_SectionHeaderStyle);
                    
                    if (m_GroupFoldoutStates[pair.Key])
                    {
                        EditorGUI.indentLevel++;
                        
                        foreach (var assetPath in pair.Value)
                        {
                            GUILayout.BeginHorizontal("box");
                            
                            // 显示资源路径
                            EditorGUILayout.SelectableLabel(assetPath, m_FilePathStyle, GUILayout.ExpandWidth(true), GUILayout.Height(18));
                            
                            // 选择资源按钮
                            if (GUILayout.Button("选择", m_SmallButtonStyle, GUILayout.Width(50)))
                            {
                                var asset = AssetDatabase.LoadMainAssetAtPath(assetPath);
                                if (asset != null)
                                {
                                    Selection.activeObject = asset;
                                    EditorGUIUtility.PingObject(asset);
                                }
                            }
                            
                            // 查看依赖按钮
                            if (GUILayout.Button("依赖", m_SmallButtonStyle, GUILayout.Width(50)))
                            {
                                var dependencies = AssetDatabase.GetDependencies(assetPath);
                                if (dependencies.Length > 0)
                                {
                                    Object[] dependencyObjects = new Object[dependencies.Length];
                                    for (int i = 0; i < dependencies.Length; i++)
                                    {
                                        dependencyObjects[i] = AssetDatabase.LoadMainAssetAtPath(dependencies[i]);
                                    }
                                    Selection.objects = dependencyObjects.Where(obj => obj != null).ToArray();
                                }
                            }
                            
                            // 删除按钮
                            if (GUILayout.Button("删除", m_SmallButtonStyle, GUILayout.Width(50)))
                            {
                                if (EditorUtility.DisplayDialog("确认删除", 
                                        $"确定要删除资源文件:\n{assetPath}\n此操作不可撤销！", 
                                        "删除", "取消"))
                                {
                                    var asset = AssetDatabase.LoadMainAssetAtPath(assetPath);
                                    if (asset != null)
                                    {
                                        AssetDatabase.DeleteAsset(assetPath);
                                        ShowNotification(new GUIContent("资源已删除"));
                                        
                                        // 标记需要重新扫描，而不是立即扫描
                                        m_NeedsRescan = true;
                                        Repaint();
                                    }
                                }
                            }
                            
                            GUILayout.EndHorizontal();
                        }
                        
                        EditorGUI.indentLevel--;
                    }
                    
                    GUILayout.EndVertical();
                    GUILayout.Space(5);
                }
                
                GUILayout.EndScrollView();
                
                GUILayout.Space(10);
                
                // 全部删除按钮
                if (GUILayout.Button("🗑️ 删除所有重复资源", m_ButtonStyle, GUILayout.Height(30)))
                {
                    if (EditorUtility.DisplayDialog("确认删除", 
                            $"确定要删除所有 {m_DuplicateAssets.Values.Sum(list => list.Count)} 个重复资源？\n此操作不可撤销！", 
                            "全部删除", "取消"))
                    {
                        int deletedCount = 0;
                        foreach (var pair in m_DuplicateAssets)
                        {
                            foreach (var assetPath in pair.Value)
                            {
                                var asset = AssetDatabase.LoadMainAssetAtPath(assetPath);
                                if (asset != null)
                                {
                                    AssetDatabase.DeleteAsset(assetPath);
                                    deletedCount++;
                                }
                            }
                        }
                        
                        ShowNotification(new GUIContent($"已删除 {deletedCount} 个资源"));
                        
                        // 标记需要重新扫描，而不是立即扫描
                        m_NeedsRescan = true;
                        Repaint();
                    }
                }
            }
            else
            {
                EditorGUILayout.LabelField("✅ 扫描完成，未发现重复资源", m_EmptyStateStyle);
            }
            
            GUILayout.EndVertical();
        }
    }
}